package com.wecon.springdemo.pattern;

/**
 * @author Weikang  Wang
 * @program: com.wecon.springdemo.pattern
 * @description: 单例模式
 * @date 2020/4/10 15:44
 */
public class Singleton {

    public static void main(String[] args) {
        Person person = Person.getInstance();
        Person person1 = Person.getInstance();
        System.out.println(person == person1);

        Car cara = Car.getInstance();
        Car carb = Car.getInstance();
        System.out.println(cara == carb);
    }

}

/**
 * 饿汉模式：一上来就创建，费内存，线程安全
 */
class Person {

    private Person() {
    }

    private static Person instance = new Person();

    public static Person getInstance() {
        return instance;
    }

}

/**
 * 懒汉模式：用的时候创建，不占内存，线程不安全
 */
class Car {
    private Car() {}
    private static Car instance = null;

    public static Car getInstance() {
        if (instance == null) {
            instance = new Car();
        }
        return instance;
    }

}